<template>
  <BasicModal title="退货" @register="register" @ok="handleSubmit">
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { returnGoods } from '@/api/page/manage_account';
  import { ref } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { searchReturnReasons } from '@/api/page/return_reason';
  const { createMessage } = useMessage();
  const emit = defineEmits(['next', 'register']);
  const schemas: FormSchema[] = [
    {
      label: '退货原因',
      field: 'returnReason',
      component: 'Select',
      required: true,
      colProps: {
        span: 24,
      },
    },
    {
      label: '具体原因',
      field: 'returnResaonData',
      component: 'InputTextArea',
      required: true,
      colProps: {
        span: 24,
      },
    },
  ];
  const id = ref<String>('');
  const [register, { closeModal }] = useModalInner((data) => {
    id.value = data.record.id || '';
    
    // 类别的选项
    searchReturnReasons({}).then((res) => {
      if (res.code === 1000) {
        let option = <any>[]
        res.obj.forEach((item) => {
          option.push({ label: item.returnReasons, value: item.returnReasons, key: item.returnReasons })
        })
        updateSchema({
          field: 'returnReason',
          componentProps: {
            options: option,
          },
        });
      }
    });

  });

  const [registerForm, { updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
    submitFunc: handleGetValues,
  });


  async function handleGetValues() {
    try {
      const values = await validate();
      const params = Object.assign({}, {id: id.value}, values);
      
      const data = await returnGoods(params);
      if (data.code === 1000) {
        createMessage.success('退货成功！');
        closeModal();
        emit('next', values);
      } else {
        createMessage.error('退货失败，请重试！');
      }
    } catch (error) {
      console.log('error', error);
      createMessage.error('请将有红色标记的填写完整');
    }
  }
  async function handleSubmit() {
    handleGetValues()
  }
</script>
